<template>
	<div class="layout-padding">
		<splitpanes>
			<pane size="20">
				<div class="layout-padding-auto layout-padding-view">
					<el-input prefix-icon="search" v-model="filterText" placeholder="请输入关键字搜索" class="mb-2" />
					<el-scrollbar>
						<el-tree
							ref="treeRef"
							:data="treeData.list"
							:props="treeData.defaultProps"
							@node-click="handleNodeClick"
							node-key="id"
							:default-expand-all="true"
							:highlight-current="true"
							:expand-on-click-node="false"
							:filter-node-method="filterNode"
						/>
					</el-scrollbar>
				</div>
			</pane>
			<pane class="ml8">
				<div class="relative layout-padding-auto layout-padding-view">
					<!-- 地图节点 -->
					<div class="w-full h-full" ref="amapRef" id="map"></div>
					<!-- 监测点类型,指标类别 -->
					<div class="site">
						<div class="flex flex-nowrap">
							<el-radio-group v-model="range" size="small" @change="toggleRange" class="!flex-nowrap">
								<el-radio-button v-for="item in rangeTime" :key="item.name" :label="item.name">
									{{ item.label }}
								</el-radio-button>
							</el-radio-group>
							<el-date-picker
								class="ml-1 !w-[300px]"
								size="small"
								v-model="dateTime"
								type="datetimerange"
								start-placeholder="开始时间"
								end-placeholder="结束时间"
								@change="handleDateChange"
								value-format="YYYY-MM-DD HH:mm:ss"
							/>
							<el-button size="small" type="primary" class="ml-1" icon="search" @click="getDataList">查询</el-button>
						</div>
						<div class="flex mt-2">
							<el-radio-group v-model="polution" size="small" @change="toggleFactorLayerAll" class="!flex-nowrap">
								<el-radio-button v-for="item in m_CurrentTypeIndicator_list" :key="item.name" :label="item.name">
									{{ item.label }}
								</el-radio-button>
							</el-radio-group>
							<el-button size="small" :type="winddirection ? '' : 'primary'" class="ml-1" @click="handleWinddirection"
								>{{ winddirection ? '隐藏' : '显示' }}风向</el-button
							>
						</div>
						<div class="flex items-center mt-2">
							<span class="min-w-[80px] text-primary">播放速度</span>
							<el-slider
								class="!w-[400px]"
								v-model="speed"
								show-input
								size="small"
								:min="200"
								:max="2000"
								:step="100"
								:show-input-controls="false"
								@change="handleSpeedChange"
							/>
						</div>
						<div class="flex items-center mt-2">
							<span class="min-w-[80px] text-[#00e400]">播放进度</span>
							<el-progress :percentage="percentage" class="!w-[300px]" color="#00e400">
								<template #default="{ percentage }">
									<span class="text-[#00e400]">{{ percentage }}%</span>
								</template>
							</el-progress>
						</div>
					</div>
				</div>
			</pane></splitpanes
		>
	</div>
</template>

<script setup lang="ts" name="cloudMap">
import { fetchList } from '/@/api/platform/cloudMap';
import { m_CurrentTypeIndicator_list, rangeTime, get$limit } from './data';
import { useScript } from '/@/hooks/web/useScript';
import { fetchAreaList as fetchTreeList } from '/@/api/platform/codeArea';
import { handleTree } from '/@/utils/other';
import Wind_Icon from '/@/assets/images/wind_dirct.png';
import { formatDate } from '/@/utils/formatTime';
interface Tree {
	[key: string]: any;
}
const A_MAP_URL = 'https://webapi.amap.com/maps?v=1.4.15&key=24a6afd6ab0b81c1bda89e736ff24c6f';
const amapRef = ref();
const { toPromise } = useScript({ src: A_MAP_URL });
let timer: any;
const speed = ref(500);
const percentage = ref(0);
const range = ref(rangeTime[0].name);
const dataList: any = ref([]);
const treeRef = ref();
const filterText = ref('');
const siteId = ref('');
// 区域树使用的数据
const treeData = reactive({
	list: [],
	defaultProps: {
		label: 'name',
	},
});
// 搜索树监听
watch(filterText, (val) => {
	treeRef.value!.filter(val);
});
const dateTime = ref<[string, string]>([
	formatDate(new Date(new Date().getTime() - 1000 * 60 * 60), 'YYYY-mm-dd HH:MM:SS'),
	formatDate(new Date(), 'YYYY-mm-dd HH:MM:SS'),
]);
const polution = ref(m_CurrentTypeIndicator_list[0].name);
const winddirection = ref(true);
const $Limit = get$limit();
let map: any;
let AMap: any;
let $heatmap: any;
let markers: any = [];
async function initMap() {
	await toPromise();
	await nextTick();
	const wrapEl = unref(amapRef);
	if (!wrapEl) return;
	AMap = (window as any).AMap;
	map = new AMap.Map(wrapEl, {
		resizeEnable: true,
		center: [104.604208, 31.51514],
		zoom: 4,
		zooms: [4, 18],
		mapStyle: 'amap://styles/fresh',
	});
	map.on('complete', function () {
		map.setCity('中国');
	});
	map.plugin(['AMap.Heatmap'], function () {
		$heatmap = new AMap.Heatmap(map, {
			radius: 50,
			opacity: [0, 0.8],
		});
	});
	renderView(true);
}

let timer_once_arr: any = [];
const renderView = (init = false) => {
	let l = $Limit[0][polution.value] || [];
	let g: any = {};
	let min = 0;
	let max = 0;
	if (l.length) {
		min = l[0]?.Con_Upper;
		max = l[l.length - 1]?.Con_Upper;
		let c = ['white', 'blue', 'rgb(117,211,248)', 'rgb(0, 255, 0)', '#ffea00', 'red', 'black'];
		for (let i = 0; i < l.length; i++) {
			let item = l[i];
			let n = (item.Con_Upper - min) / (max - min);
			g[n] = c[i];
		}
		$heatmap.setOptions({
			radius: 50,
			opacity: [0, 0.8],
			gradient: g,
		});
	}

	if (init && dataList.value.length && l.length) {
		initMarker(max, min, dataList.value[0].list);
		nextTick(() => {
			// map.setFitView(markers);
		});
	}
	timer = window.clearInterval(timer);
	timer = setInterval(() => {
		setSpeedPercentage(max, min);
	}, speed.value * dataList.value.length);
	setSpeedPercentage(max, min);
};
const setSpeedPercentage = (max: number, min: number) => {
	for (let i = 0; i < dataList.value.length; i++) {
		const v = dataList.value[i].list;
		let timer_once = setTimeout(() => {
			if (!dataList.value.length) {
				window.clearTimeout(timer_once);
				for (let i = 0; i < timer_once_arr.length; i++) {
					window.clearTimeout(timer_once_arr[i]);
				}
				return false;
			}
			initMarker(max, min, v);
			percentage.value = Number((((i + 1) / dataList.value.length) * 100).toFixed(1));
		}, speed.value * i);
		timer_once_arr.push(timer_once);
	}
};
const initMarker = (max: number, min: number, v: any) => {
	markers.length && map.remove(markers);
	let content: any = [];
	if (winddirection.value) {
		for (let i = 0; i < v.length; i++) {
			const pos: [number, number] = [v[i].longitude, v[i].latitude];
			const marker = getMarkers(pos, v[i].windDirection);
			markers.push(marker);
		}
	}
	v.forEach((d: any) => {
		let c = {
			lng: d.longitude,
			lat: d.latitude,
			count: d[polution.value.toLowerCase()],
		};
		content.push(c);
	});
	$heatmap.setDataSet({
		data: content,
		max: max - min,
	});
};
function getMarkers(position: [number, number], WindDirection: number) {
	const icon = new AMap.Icon({
		size: new AMap.Size(20, 30),
		// 图标的取图地址
		image: Wind_Icon,
		// 图标所用图片大小
		imageSize: new AMap.Size(20, 30),
	});
	const marker = new AMap.Marker({
		clickable: false,
		icon: icon,
		position: position,
	});
	marker.setOffset(new AMap.Pixel(-9.5, -16.5));
	marker.setAngle(WindDirection * -22.5);
	marker.setMap(map);
	return marker;
}
const handleWinddirection = () => {
	winddirection.value = !winddirection.value;
	if (!winddirection.value) {
		markers.length && map.remove(markers);
	} else {
		markers.length && map.add(markers);
	}
};
const toggleFactorLayerAll = () => {
	getDataList();
};
const toggleRange = () => {
	getDataList();
};
const handleDateChange = () => {
	getDataList();
};
const handleSpeedChange = () => {
	resetRenderView();
	renderView();
};
const getDataList = () => {
	fetchList({ dt0: dateTime.value[0], dt1: dateTime.value[1], tp: range.value, tag: siteId.value }).then((res) => {
		dataList.value = res.data;
		resetRenderView();
		if (res.data.length) {
			renderView(true);
		}
	});
};
const resetRenderView = () => {
	for (let i = 0; i < timer_once_arr.length; i++) {
		window.clearTimeout(timer_once_arr[i]);
	}
	$heatmap &&
		$heatmap?.setDataSet({
			data: [],
		});
	percentage.value = 0;
	window.clearInterval(timer);
	markers.length && map.remove(markers);
};
// 点击树
const handleNodeClick = (e: any) => {
	siteId.value = e.id;
	getDataList();
};

const getTreeDate = async () => {
	await fetchTreeList().then((res: any) => {
		const records = res.data;
		if (records.length) {
			treeData.list = handleTree(records, 'id', 'pid', 'children', '1111111111111111111');
			siteId.value = treeData.list[0]?.id;
			getDataList();
			nextTick(() => {
				unref(treeRef)?.setCurrentKey(siteId.value, true);
			});
		}
	});
};
const filterNode = (value: string, data: Tree) => {
	if (!value) return true;
	return data.name.includes(value);
};
onMounted(() => {
	initMap();
	getTreeDate();
});
onUnmounted(() => {
	window.clearInterval(timer);
});
</script>

<style lang="scss" scoped>
:deep(.amap-marker-label) {
	color: #000;
	background: #00e400;
	border: unset;
	border-radius: 4px;
}
:deep(.amap-logo) {
	display: none !important;
}
:deep(.amap-copyright) {
	display: none !important;
}

.site {
	position: absolute;
	top: 15px;
	left: 50%;
	transform: translateX(-50%);
	//z-index: 99;
}
</style>
